#!/bin/bash
set -e

cd $(dirname $0)

if [[ -z ${BRANCH} ]]; then
    branch=$(git rev-parse --abbrev-ref HEAD)
else
    echo "Using branch ${BRANCH}"
    branch=${BRANCH}
fi

if [[ -z ${REPOSITORY} ]]; then
    echo "Need to provide REPOSITORY as environment variable"
    exit 1
fi

cd ..

# Setup
rm -rf ./repository
mkdir -p ./repository
cd repository

# Pull in branch
echo "Pulling in ${REPOSITORY}@${branch}"
git clone --depth 1 --branch ${branch} ${REPOSITORY} . > /dev/null 2>&1

if ! (test -d assets && test -d charts); then
    echo "There are no charts or assets in this repository"
    cd ..
    rm -rf ./repository
    exit 1
fi

# Copy assets and charts into the new format
for package_assets in assets/*; do
    cp -R ${package_assets} ../assets
    package_name=$(basename -- ${package_assets})
    for asset in ${package_assets}/*; do
        if [[ ${asset} =~ .*\.tgz ]]; then
            # Parse structure
            asset_name=$(basename -- ${asset%.*})
            chart_name=$(echo ${asset_name} | rev | cut -d- -f2- | rev)
            chart_name=$(echo ${chart_name} | sed -r 's/-[[:digit:]\.]+$//')
            chart_version=${asset_name#${chart_name}-}
            
            # Fix chart version for rc version
            # e.g. 0.0.0-rc100 -> 0.0.000-rc1 to keep the drop release candidate version logic simple
            if [[ ${chart_version} =~ [0-9]{2}$ ]] && [[ ${chart_version} =~ -rc ]]; then
                actual_version=${chart_version%-*}
                package_version=${chart_version: -2}
                chart_version_without_package_version=${chart_version%${package_version}}
                rc_version=${chart_version_without_package_version#${actual_version}}
                chart_version=${actual_version}${package_version}${rc_version}
            fi

            # Dump archives as charts
            chart_path=../charts/${package_name}/${chart_name}/${chart_version}
            echo "Unarchiving ${asset} to ${chart_path}"
            mkdir -p ${chart_path}
            tar xvzf ${asset} -C ${chart_path} --strip-components=1 > /dev/null 2>&1
        fi
    done
done

# Go back
cd ..
helm repo index --merge ./assets/index.yaml --url assets assets
mv ./assets/index.yaml ./index.yaml
rm -rf ./repository